# coding=utf-8

"""
    Created by Kalyter on 2018-01-25.
"""
import os

import xlrd
from xlutils import copy

from learning.scientifc.jobs.job import Job
from learning.scientifc.readers.reader import ReaderFactory
from learning.util.log_util import get_logger

logger = get_logger()


class FillUpJob(Job):
    name = '填充作业'

    def __init__(self, app):
        super().__init__(app)
        self.fill_source = self.app.config.get('FILL_SOURCE')
        self.fill_gdp = self.app.config.get('FILL_GDP')
        self.fill_other = self.app.config.get('FILL_OTHER')
        self.fill_tariff = self.app.config.get('FILL_TARIFF')
        self.europe_countries = self.app.config.get('EUROPE_COUNTRIES')
        self.europe_name = self.app.config.get('EUROPE_NAME')
        self.factory = ReaderFactory(app)
        self.fill_target = '%s-result.xls' % \
                           os.path.splitext(self.fill_source)[0]

    def run(self, gdp=True, tariff=True, other=True):
        logger.info('开始加载目标文件')
        raw = xlrd.open_workbook(self.fill_source)
        workbook = copy.copy(raw)
        sheet = workbook.get_sheet(0)
        source_reader = self.factory.create(self.fill_source)
        logger.info('加载完成')

        if gdp:
            logger.info('开始填充GDP部分')
            self.fill_gdp_part(source_reader, sheet)
            logger.info('填充GDP完成')

        if tariff:
            logger.info('开始填充关税')
            self.fill_tariff_part(source_reader, sheet)
            logger.info('填充关税部分完成')

        if other:
            logger.info('开始填充其他部分')
            self.fill_other_part(source_reader, sheet)
            logger.info('其他部分填充完成')

        logger.info('正在保存文件 %s', self.fill_target)
        workbook.save(self.fill_target)
        logger.info('保存成功')

    def fill_other_part(self, source_reader, sheet):
        other_reader = self.factory.create(self.fill_other)
        other_header = other_reader.row_values(0)
        headers = source_reader.row_values(0)
        conting_column = headers.index('contig')
        comcol_column = headers.index('concol')
        dist_column = headers.index('dis')

        other_name_column = other_header.index('iso_d')
        other_conting_column = other_header.index('contig（是否接壤）')
        other_comcol_column = other_header.index('comcol')
        other_dist_column = other_header.index('dist')

        for i, country in other_reader.range(1):
            country_name = country[other_name_column]
            conting = country[other_conting_column]
            comcol = country[other_comcol_column]
            dist = country[other_dist_column]
            for t in range(1, source_reader.nrows):
                source_row = source_reader.row_values(t)
                if country_name == source_row[0]:
                    sheet.write(t, conting_column, conting)
                    sheet.write(t, comcol_column, comcol)
                    sheet.write(t, dist_column, dist)
            logger.info('%s 其他信息填充完成', country_name)

    def fill_tariff_part(self, source_reader, sheet):
        headers = source_reader.row_values(0)
        tariff_reader = self.factory.create(self.fill_tariff)
        tariff_header = tariff_reader.row_values(0)
        tariff_column = headers.index('tarrif')

        tariff_name_column = tariff_header.index('reportor')
        tariff_year_column = tariff_header.index('year')
        tariff_hs_column = tariff_header.index('HS code')
        tariff_tariff_column = tariff_header.index('tarrif')

        logger.info('开始寻找欧盟数据')
        europe_data = []
        for i, country in tariff_reader.range(1):
            country_name = country[tariff_name_column]
            if country_name == self.europe_name:
                country_year = str(float(country[tariff_year_column]))
                country_hs = country[tariff_hs_column]
                country_tariff = country[tariff_tariff_column]
                europe_data.append((country_year, country_hs, country_tariff))
        logger.info('寻找完成')

        for t, source_row in source_reader.range(1):
            if source_row[0] in self.europe_countries:
                for year, hs, tariff in europe_data:
                    if year == str(source_row[1]) \
                            and hs == source_row[2]:
                        sheet.write(t, tariff_column, tariff)
                        break

        for i, country in tariff_reader.range(1):
            country_name = country[tariff_name_column]
            country_year = str(float(country[tariff_year_column]))
            country_hs = country[tariff_hs_column]
            country_tariff = country[tariff_tariff_column]
            for t, source_row in source_reader.range(1):
                if country_name == source_row[0] \
                        and country_year == str(source_row[1]) \
                        and country_hs == source_row[2]:
                    sheet.write(t, tariff_column, country_tariff)
                    break

    def fill_gdp_part(self, source_reader, sheet):
        headers = source_reader.row_values(0)
        gdp_reader = self.factory.create(self.fill_gdp)
        source_year_column = headers.index('Year')
        gdp_column = headers.index('GDPit')
        gdp_china_column = headers.index('GDPct(中国)')
        china_header = 'China'

        gdp_china = None
        for i, country in gdp_reader.range(1):
            if country[0] == china_header:
                gdp_china = country
                gdp_reader.remove(i)
                break

        gdp_headers = gdp_reader.row_values(0)
        gdp_name_column = gdp_headers.index('Country Name')

        for i, country in gdp_reader.range(1):
            country_name = country[gdp_name_column]
            logger.info('开始插入 %s GDP', country_name)
            for t, source_row in source_reader.range(1):
                if country_name == source_row[0]:
                    source_year = str(int(source_row[source_year_column]))
                    gdp_year_column = gdp_headers.index(source_year)
                    country_gdp = country[gdp_year_column]
                    sheet.write(t, gdp_column, country_gdp)
                    sheet.write(t, gdp_china_column,
                                gdp_china[gdp_year_column])
            logger.info('%s GDP插入完成', country_name)
